package com.lifuixng.picturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lifuixng.picturebackend.common.DeleteRequest;
import com.lifuixng.picturebackend.exception.BusinessException;
import com.lifuixng.picturebackend.exception.ErrorCode;
import com.lifuixng.picturebackend.exception.ThrowUtils;
import com.lifuixng.picturebackend.manage.cache.CacheManage;
import com.lifuixng.picturebackend.manage.upload.FilePictureUpload;
import com.lifuixng.picturebackend.manage.upload.PictureUploadTemplate;
import com.lifuixng.picturebackend.manage.upload.UrlPictureUpload;
import com.lifuixng.picturebackend.model.dto.picture.*;
import com.lifuixng.picturebackend.model.dto.file.UploadPictureResult;
import com.lifuixng.picturebackend.model.entity.Picture;
import com.lifuixng.picturebackend.model.entity.Space;
import com.lifuixng.picturebackend.model.entity.User;
import com.lifuixng.picturebackend.model.enums.PictureReviewStatusEnum;
import com.lifuixng.picturebackend.model.mapping.PictureMapping;
import com.lifuixng.picturebackend.model.mapping.UserMapping;
import com.lifuixng.picturebackend.model.vo.picture.PictureVO;
import com.lifuixng.picturebackend.model.vo.user.UserVO;
import com.lifuixng.picturebackend.service.PictureService;
import com.lifuixng.picturebackend.mapper.PictureMapper;
import com.lifuixng.picturebackend.service.SpaceService;
import com.lifuixng.picturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 26966
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2024-12-17 13:46:01
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {


    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private UserService userService;
    @Resource
    private UserMapping userMapping;

    @Resource
    private PictureMapping pictureMapping;

    @Resource
    private CacheManage cacheManage;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    /**
     * 文件上传或更改
     *
     * @param inputSource          文件
     * @param pictureUploadRequest 图片id
     * @param loginUser            当前登录的用户
     * @return
     */
    @Override
    public PictureVO uploadPicture(
            Object inputSource,
            PictureUploadRequest pictureUploadRequest,
            User loginUser
    ) {

        // 校验参数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_FOUND_ERROR);
        // 检验图片是否上传到私人空间，指定spaceId就表示上传到指定的私人空间
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            // 上传到私人空间
            // 查看是否有这个空间
            Space space = spaceService.getBaseMapper().selectById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "该用户没有空间");
            // 空间存在 判断是否有上传权限（当前登录人的id是否和空间所有者userId一样）
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            // 校验空间额度
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }

        Long pictureId = pictureUploadRequest.getId();
        // 如果pictureId为空说明是添加图片，当图片修改才会有id
        // 图片存在 ( 修改图片)
        if (pictureId != null) {
            // 查询数据库是否存在
            Picture oldPicture = this.baseMapper.selectById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 仅图片本人和管理员才可以更行
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }

            // 校验空间是否一致
            if (spaceId != null) {
                // 空间存在 判断原来图片的空间是否和传来的空间一致
                if (!Objects.equals(oldPicture.getSpaceId(), spaceId)) {
                    // 不一致
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "更改图片的空间id不一致");

                }
            } else {
                // 没传spaceId,将原来图片的空间id赋值给space
                spaceId = oldPicture.getSpaceId();

            }
        }
        // 图片不存在 则为上传图片
        // 上传前缀（文件夹目录），通过id划分（每个用户上传的图片放在自己的文件夹中）
        String uploadPathPrefix = null;
        if (spaceId == null) {
            // 公共空间
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        // 图片上传
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        // 如果传来的是String类型就为URL上传
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest.getPicName() != null) {
            picName = pictureUploadRequest.getPicName();
        }
        Picture picture = Picture.builder()
                .url(uploadPictureResult.getUrl())
                .thumbnailUrl(uploadPictureResult.getThumbnailUrl())
                .name(picName)
                .picSize(uploadPictureResult.getPicSize())
                .picWidth(uploadPictureResult.getPicWidth())
                .picHeight(uploadPictureResult.getPicHeight())
                .picScale(uploadPictureResult.getPicScale())
                .picFormat(uploadPictureResult.getPicFormat())
                .userId(loginUser.getId())
                .spaceId(spaceId)
                .build();
        this.fillReviewParams(picture, loginUser);
        // 存到数据库（添加或更新） 根据id是否存在来进行判断
        // 图片存在-----》编辑
        if (pictureId != null) {
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        picture.setCreateTime(new Date());

        Long finalSpaceId = spaceId;

        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            // 如果是上传到空间的图片，更新空间的容量
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        //  totalSize = totalSize+picture.getSize() 更改容量
                        // totalCount = totalCount+1  更改条数
                        .setSql("totalSize= totalSize+" + picture.getPicSize())
                        .setSql("totalCount = totalCount+1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "空间额度更新失败");
            }
            return picture;
        });
        // 如果picture有id就是更新 否则就是添加

        return PictureVO.objToVo(picture);
    }

    /**
     * 删除图片 仅管理员才可以删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @Override
    public int deleteById(DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null && deleteRequest.getId() < 0, ErrorCode.PARAMS_ERROR);
        // 查看当前图片是否存在
        Picture oldPicture = this.baseMapper.selectById(deleteRequest.getId());
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 权限校验
        User loginUser = userService.userLoginInfo(request);
        this.checkPictureAuth(loginUser, oldPicture);
        // 才可以删除
        int result = this.baseMapper.deleteById(deleteRequest.getId());
        ThrowUtils.throwIf(result <= 0, ErrorCode.OPERATION_ERROR);
        // 更新空间额度
        // 清空缓存
        // cacheManage.deleteCacheValue();
        return result;
    }

    @Override
    public int editPicture(PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        // 判空
        ThrowUtils.throwIf(pictureEditRequest == null, ErrorCode.PARAMS_ERROR);
        // 转换 赋值
        Picture picture = pictureMapping.pictureEditRequestToPicture(pictureEditRequest);
        String tagsStr = JSONUtil.toJsonStr(pictureEditRequest.getTags());
        picture.setTags(tagsStr);
        // 当前登录的用户
        User user = userService.userLoginInfo(request);
        this.fillReviewParams(picture, user);
        // 数据校验
        this.verifyPicture(picture);
        // 判断图片是否存在
        Picture oldPicture = this.baseMapper.selectById(pictureEditRequest.getId());
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 权限校验
        User loginUser = userService.userLoginInfo(request);
        this.checkPictureAuth(loginUser, oldPicture);
        // 数据库更新
        picture.setEditTime(new Date());
        int result = this.baseMapper.updateById(picture);
        ThrowUtils.throwIf(result <= 0, ErrorCode.OPERATION_ERROR);
        // cacheManage.deleteCacheValue();
        return result;
    }

    /**
     * 更改图片（仅管理员才可以）
     *
     * @param pictureUpdateRequest
     * @return
     */
    @Override
    public int updatePicture(PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null && pictureUpdateRequest.getId() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 查看图片是否存在
        Picture resultPicture = this.baseMapper.selectById(pictureUpdateRequest.getId());
        ThrowUtils.throwIf(resultPicture == null, ErrorCode.NOT_FOUND_ERROR);

        Picture picture = pictureMapping.pictureUpdateRequestToPicture(pictureUpdateRequest);
        // 将list转换成字符串
        String tagsStr = JSONUtil.toJsonStr(pictureUpdateRequest.getTags());
        picture.setTags(tagsStr);
        User loginUser = userService.userLoginInfo(request);
        this.fillReviewParams(picture, loginUser);
        // 图片校验
        this.verifyPicture(picture);

        // 存在照片执行更改
        int result = this.baseMapper.updateById(picture);
        ThrowUtils.throwIf(result <= 0, ErrorCode.OPERATION_ERROR);
        // cacheManage.deleteCacheValue();
        return result;
    }


    /**
     * 根据id获取图片 仅仅管理员
     *
     * @param id
     * @return
     */
    @Override
    public Picture getPictureById(Long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = this.baseMapper.selectById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        return picture;
    }


    @Override
    public PictureVO getPictureVOById(Long id, HttpServletRequest request) {

        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = this.baseMapper.selectById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);

        // 查看的是公共的还是私人空间的？
        if (picture.getSpaceId() != null) {
            // 私人空间
            User loginUser = userService.userLoginInfo(request);
            this.checkPictureAuth(loginUser, picture);
        }
        PictureVO pictureVO = PictureVO.objToVo(picture);
        Long userId = picture.getUserId();
        // 图片存在userid，进行查询用户
        if (userId != null && userId > 0) {
            User user = userService.getUserById(userId);
            UserVO userVO = userMapping.userToUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 校验图片
     *
     * @param picture
     */
    @Override
    public void verifyPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "图片URL过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 200, ErrorCode.PARAMS_ERROR, "图片简介");
        }
    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);

        PictureVO pictureVO = PictureVO.objToVo(picture);
        Long userId = picture.getUserId();
        // 图片存在userid，进行查询用户
        if (userId != null && userId > 0) {
            User user = userService.getUserById(userId);
            UserVO userVO = userMapping.userToUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userMapping.userToUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }


    /**
     * 将请求条件转为条件构造器
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        // 对象为空 没有查询条件
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();


        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        // 根据空间id查询私有图库的图片
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        // 如果未null，查询spaceId字段为null的数据
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.ge(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);

        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 分页查询，管理员才可以
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public Page<Picture> pictureListByPage(PictureQueryRequest pictureQueryRequest) {

        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();

        return this.page(new Page<>(current, pageSize), this.getQueryWrapper(pictureQueryRequest));

    }

    /**
     * 分页查询 普通用户
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @Override
    public Page<PictureVO> pictureVOListByPage(PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {

        // String cacheValue = null;
        // // 获取缓存key
        // String cacheKey = cacheManage.CacheKey(pictureQueryRequest);
        // // 在缓存中查询
        // cacheValue = cacheManage.getCacheValue(cacheKey);
        // if (cacheValue != null) {
        //     return JSONUtil.toBean(cacheValue, Page.class);
        // }

        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        if (pictureQueryRequest.getSpaceId() == null) {
            // 公共空间的查询条件 只展示审核通过的图片
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            // 私人空间,判断是否有查看的权限（空间所有者）
            // 查询空间
            Space space = spaceService.getBaseMapper().selectById(pictureQueryRequest.getSpaceId());
            ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
            User loginUser = userService.userLoginInfo(request);
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        Page<Picture> picturePage = this.page(new Page<>(current, pageSize), this.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOPage = this.getPictureVOPage(picturePage, request);

        // 将查询结果放入缓存中
        // cacheManage.putCacheValue(cacheKey, JSONUtil.toJsonStr(pictureVOPage));

        return pictureVOPage;
    }


    /**
     * 填充审核参数
     *
     * @param picture
     * @param loginUser
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {

        // 校验参数
        ThrowUtils.throwIf(picture == null && loginUser == null, ErrorCode.PARAMS_ERROR);
        // 判断权限 （如果登录的用户是管理员将审核状态设成通过，否则为待审核）
        // TODO
        if (userService.isAdmin(loginUser) || picture.getSpaceId() != null) {
            picture.setReviewerId(loginUser.getId());
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewMessage("自动过审");
            picture.setReviewTime(new Date());
        } else {
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }

    }


    /**
     * 图片审核功能
     *
     * @param pictureReviewRequest
     * @param loginUser
     * @return
     */
    @Override
    public int doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {

        // 参数校验
        ThrowUtils.throwIf(pictureReviewRequest == null && loginUser == null, ErrorCode.PARAMS_ERROR);
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        // 通过值获取对应的枚举
        PictureReviewStatusEnum pictureReviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (id == null || pictureReviewStatusEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断图片是否存在
        Picture oldPicture = this.baseMapper.selectById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.PARAMS_ERROR);
        if (reviewStatus.equals(oldPicture.getReviewStatus())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }

        Picture picture = pictureMapping.pictureReviewRequestToPicture(pictureReviewRequest);
        picture.setReviewerId(loginUser.getId());
        picture.setReviewTime(new Date());
        // 更新审核状态
        int result = this.baseMapper.updateById(picture);
        ThrowUtils.throwIf(result == 0, ErrorCode.OPERATION_ERROR);
        return result;
    }

    /**
     * 批量抓取上传图片
     *
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {

        // 搜索词
        String searchText = pictureUploadByBatchRequest.getSearchText();
        // 搜索条数
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多抓取30条");
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);

        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("图片抓取失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片抓取失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }

        // 图片集合
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element element : imgElementList) {

            String fileUrl = element.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("图片链接为空,{}", fileUrl);
                continue;
            }
            // 去除特殊符号
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }

            try {
                // 文件上传
                PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();

                String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
                // 如果没有填写前缀 搜索词为图片名
                if (StrUtil.isBlank(namePrefix)) {
                    namePrefix = pictureUploadByBatchRequest.getSearchText();
                }
                pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.error("图片上传成功id：{}", pictureVO.getId());
                if (uploadCount++ >= count - 1) {
                    break;
                }
            } catch (Exception e) {
                log.error("图片上传失败");
                continue;
            }


        }

        // cacheManage.deleteCacheValue();
        return uploadCount;


    }

    /**
     * 删除和编辑图片 权限校验
     *
     * @param loginUser
     * @param picture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {

        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库 只有管理员和图片所有者才可以操作
            if (!userService.isAdmin(loginUser) && !picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有图库 仅空间管理员可以
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }
}




